package com.evendai.sipdemo.util

import android.app.Activity
import android.content.Intent
import com.evendai.loglibrary.Timber
import com.evendai.sipdemo.App
import com.evendai.sipdemo.LoginActivity
import org.doubango.utils.Util
import org.jetbrains.anko.startActivity

object ActivityUtil {

    private val activities = mutableListOf<Activity>()

    fun getTopActivity(): Activity? {
        return if (activities.isNotEmpty()) activities.last() else null
    }

    fun getAnyActivity(): Activity? {
        return activities.find { !it.isFinishing }
    }

    fun addActivity(activity: Activity) {
        if (!activities.contains(activity)) {
            activities.add(activity)
        }
    }

    fun removeActivity(activity: Activity) {
        activities.remove(activity)
    }

    fun finishAllActivity() {
        activities.forEach { it.finish() }
    }

    /** 跳转到MainActivity，只保留MainActivity，结束其它所有的Activity */
    fun gotoMainActivity() {
        val hasLoginActivity = activities.find { it is LoginActivity && !it.isFinishing } != null
        if (hasLoginActivity) {
            // 如果本来就有登录界面了
            Timber.fe(Exception(), "LoginActivity连着开了多个")
        } else {
            val anyActivity = getAnyActivity()
            if (anyActivity == null) {
                val intent = Intent(App.getContext(), LoginActivity::class.java)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                Util.startActivityAsUser(intent)
            } else {
                anyActivity.startActivity<LoginActivity>()
            }
        }

        finishAllActivityExceptLoginActivity()
    }

    /** finish掉所有Activity，LoginActivity除外 */
    private fun finishAllActivityExceptLoginActivity() {
        val iterator = activities.listIterator()
        while (iterator.hasNext()) {
            val activity = iterator.next()
            if (activity !is LoginActivity) {
                activity.finish()
                iterator.remove()
            }
        }
    }

}